#!/usr/bin/env python3
import sys
import rclpy
from rclpy.node import Node
from example_interfaces.srv import AddTwoInts


class AddTwoIntsClient(Node):
    def __init__(self):
        super().__init__('add_two_ints_client')

        # 创建服务客户端
        self.client = self.create_client(AddTwoInts, 'add_two_ints')

        # 等待服务可用
        while not self.client.wait_for_service(timeout_sec=1.0):
            self.get_logger().info('服务不可用，等待中...')

    def send_request(self, a: int, b: int):
        """发送加法请求"""
        request = AddTwoInts.Request()
        request.a = a
        request.b = b

        self.get_logger().info(f'发送请求: {a} + {b}')

        # 异步调用服务
        future = self.client.call_async(request)
        return future


def main(args=None):
    rclpy.init(args=args)

    # 检查命令行参数
    if len(sys.argv) != 3:
        print("用法: python3 add_two_ints_client.py <数字1> <数字2>")
        return

    try:
        a = int(sys.argv[1])
        b = int(sys.argv[2])
    except ValueError:
        print("请输入有效的整数")
        return

    node = AddTwoIntsClient()

    # 发送请求
    future = node.send_request(a, b)

    # 等待响应
    rclpy.spin_until_future_complete(node, future)

    if future.result() is not None:
        response = future.result()
        node.get_logger().info(f'收到结果: {response.sum}')
    else:
        node.get_logger().error('服务调用失败')

    node.destroy_node()
    rclpy.shutdown()


if __name__ == '__main__':
    main()